package com.example.app1;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class AIDLServiceActivity extends AppCompatActivity {

    final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);

            EditText num1 = findViewById(R.id.num1);
            EditText num2 = findViewById(R.id.num2);
            double a =  Double.parseDouble(num1.getText().toString());
            double b =  Double.parseDouble(num2.getText().toString());

            double res1 = 0;
            double res2 = 0;
            double res3 = 0;

            try {
                res1 = iMyAidlInterface.plus(a,b);
                res2 = iMyAidlInterface.minus(a,b);
                res3 = iMyAidlInterface.multiply(a,b);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
            Toast.makeText(AIDLServiceActivity.this,"返回的结果：加"+res1+" 减："+res2+" 乘："+res3,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("AIDLServiceActivity","释放Service");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidlservice);

    }


    public void calculate(View view) throws InterruptedException {
        Intent intent = new Intent(this, MyService.class);
        //绑定
        bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);

    }
}